﻿using System;
using System.Windows;
using System.Windows.Controls;
using Microsoft.Practices.Composite.Events;
using Microsoft.Practices.Composite.Wpf.Commands;
using WpfTwitterClient.Infrastructure;
using WpfTwitterClient.Infrastructure.Services;
using WpfTwitterClient.Modules.Authorization.Views.StatusView;

namespace WpfTwitterClient
{
    /// <summary>
    /// Interaction logic for Page1.xaml
    /// </summary>
    public partial class AccountView : UserControl, IAccountView
    {
        #region Fields

        public DelegateCommand<string> myCommand;
        private ITwitterClient twitterClient;
        private InfrastructureCommandProxy proxy;

        #endregion

        #region Constructors

        public AccountView(InfrastructureCommandProxy proxy, ITwitterClient twitterClient)
        {
            this.proxy = proxy;
            this.twitterClient = twitterClient;
            myCommand = new DelegateCommand<string>(ApplicationResetCommandHandler, CanReset);
            proxy.ApplicationResetCommands.RegisterCommand(myCommand);
            InitializeComponent();
        }

        public bool CanReset(string str)
        {
            return twitterClient.IsAuthorized;
        }

        private void ApplicationResetCommandHandler(string input)
        {
            twitterClient.Reset();
            myCommand.RaiseCanExecuteChanged();
        }


        #endregion

        #region Properties

        #endregion

        #region UI Events

        public event EventHandler GetTwitterPin = delegate { }; 
        public event EventHandler<DataEventArgs<string>> AuthorizeApp = delegate { }; 

        #endregion

        public AccountPresentationModel Model
        {
            get { return this.DataContext as AccountPresentationModel; }
            set { this.DataContext = value; }
        }

        private void CommandBinding_CanExecute(object sender, System.Windows.Input.CanExecuteRoutedEventArgs e)
        {
            e.CanExecute = !Validation.GetHasError(txtPin);
        }

        private void CommandBinding_Executed(object sender, System.Windows.Input.ExecutedRoutedEventArgs e)
        {
            
            AuthorizeApp(this, new DataEventArgs<string>(this.Model.Pin));
        }

        private void image1_MouseLeftButtonDown(object sender, System.Windows.Input.MouseButtonEventArgs e)
        {
            GetTwitterPin(this, new EventArgs());
            e.Handled = true;
        }

    }
}
